import { message } from 'antd';
import { list, create, edit, dele } from '../services/special';
import tools from '../../../utils';

export default {
  namespace: 'special',

  state: {
    allData: [],
    sysData: [], // 系部数据
    specData: [], // 专业数据
    success: true,
  },

  effects: {
    *listAll({ payload }, { call, put }) {
      const response = yield call(list, payload);
      yield put({ type: 'callbackListAll', response });
    },
    *create({ payload }, { call, put }) {
      const response = yield call(create, payload);
      yield put({ type: 'callbackSave', response });
    },
    *edit({ payload }, { call, put }) {
      const response = yield call(edit, payload);
      yield put({ type: 'callbackSave', response });
    },
    *dele({ payload }, { call, put }) {
      const response = yield call(dele, payload);
      yield put({ type: 'callbackSave', response });
    },
  },

  reducers: {
    callbackListAll(st, { response }) {
      const state = st;
      if (response.success) {
        const data = response.root;

        state.sysData = [];
        state.specData = [];
        const allData = [];
        const mappingName = {}; // 根据id获取name

        for (let i = 0; i < data.length; i += 1) {
          const item = data[i];
          const { name, id, pid, types } = item;
          const isSpec = pid > 0; // 系部或专业: 0系部, >0专业
          if (isSpec) {
            if (types.length <= 2) item.types = [];
            else {
              try {
                item.types = JSON.parse(types);
              } catch(e) {
                item.types = [];
              }
            }
            state.specData.push(item);
          } else {
            state.sysData.push(item);
            mappingName[id] = name;
          }
          allData.push({
            ...item,
            key: id,
            title: name,
            selectable: !isSpec,
          });
        }

        state.allData = tools.funcPidToChildren(allData, 'id', 'pid', 'children', true);
        state.specData = state.specData.map((item) => {
          return {
            ...item,
            pName: mappingName[item.pid],
          };
        });
      }
      return { ...state };
    },
    callbackSave(st, { response }) {
      const state = st;
      state.success = response.success;
      if (response.success) message.success(response.msg);
      return { ...state };
    },
  },
};
